package com.qf.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class DynamicRouteFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER  + 10000;
    }

    @Override
    public boolean shouldFilter() {
        // 动态获取  false, true
        return true;
    }

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Object run() throws ZuulException {
        //1. 获取到request
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //2. 接收dynamic参数
        String dynamic = request.getParameter("dynamic");

        //3. 将路由规则,修改为存放在Redis中的路由规则
        String serviceId = redisTemplate.opsForValue().get("dynamic:" + dynamic + ":serviceId");
        String requestURI = redisTemplate.opsForValue().get("dynamic:" + dynamic + ":requestURI");
        if(!StringUtils.isEmpty(serviceId) && !StringUtils.isEmpty(requestURI)) {
            context.put(FilterConstants.SERVICE_ID_KEY, serviceId);
            context.put(FilterConstants.REQUEST_URI_KEY, requestURI);
        }

        return null;
    }
}
